/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dca.sistemascontrole.util;

import com.thoughtworks.xstream.XStream;
import java.io.*;

/**
 *
 * @author Rafael
 */
public class XMLManager {

    /**
     * Cria um XML a partir da instancia de um objeto e o escreve na pasta desejada.
     *
     * @param object instancia que sera usada pra gerar o xml
     * @param fileName nome do arquivo onde o xml sera escrito.
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static void writeObject(Object object, String xmlLocation) throws FileNotFoundException, IOException {
        XStream xStream = new XStream();
        String xml = xStream.toXML(object);

        File file = new File(xmlLocation);
        Writer output = new BufferedWriter(new FileWriter(file));
        try {
            output.write(xml);
        } finally {
            output.close();
        }
    }

    /**
     * Procura um xml em um endereço.
     *
     * @param <T> objeto contido no xml.
     * @param xmlLocation string contendo o caminho absoluto para o arquivo.
     * @return
     */
    public static <T> T readObject(String xmlLocation) throws FileNotFoundException, IOException {
        Object objectRead = null;
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(new File(xmlLocation));

            XStream xStream = new XStream();
            objectRead = xStream.fromXML(fileInputStream);
        } finally {
            if (fileInputStream != null) {
                fileInputStream.close();
            }
        }


        return (T) objectRead;
    }
}
